/**
 * 
 */
package com.ken.work.tools.tools.generation;

import java.io.File;
import java.io.FileWriter;
import java.util.List;

import com.ken.work.tools.tools.Contants;
import com.ken.work.tools.tools.db.DBUtil;
import com.ken.work.tools.tools.freemarker.FreeMarkerUtil;
import com.ken.work.tools.tools.model.DaoModel;
import com.ken.work.tools.tools.utils.UnderlineCamel;

import cn.hutool.core.io.FileUtil;
import freemarker.template.Template;

/**
 * @desc {生成java dao 的工具类}
 * @author Liuk
 * @date 2017年4月20日 下午7:44:26
 * @version v1.0-
 */
public class DaoRunning {
	
	/**
	 * 生成dao代码
	 * @param packageName package包
	 * @param filePath 导出到哪个路径
	 * @throws Exception
	 */
	public static void generation(){
		try {
			System.out.println("---------------code generation {{dao}} running ----------------");
			//获取数据中的所有表
			List<String> tableList = DBUtil.getTableName();
			for (String tableName : tableList) {
				generation(tableName);
			}
			System.out.println("---------------code generation {{dao}} end-----------------");
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("---------------code generation {{dao}} failed-----------------");
			e.printStackTrace();
		}
		
	}
	
	public static void generation(String tableName) throws Exception{
		DaoModel model = getDaoModel(tableName);
		Template template = FreeMarkerUtil.getTemplate("repository.ftl");
		System.out.println("---------------code generation {{table}} " + tableName +" {{Class}} " + model.getClassName() + " successed-----------------");
		FileWriter fileWriter = new FileWriter(FileUtil.newFile(Contants.Dao.getOutPath(model.getModelName()) + File.separator + model.getClassName() + ".java"));
		template.process(model, fileWriter);
	}
	
	private static DaoModel getDaoModel(String tableName){
		DaoModel model = new DaoModel();
		String className = UnderlineCamel.underline2Camel(tableName, true,Contants.table_pre);
		className = UnderlineCamel.getFirstUpper(className);
		model.setClassName(className + "Repository");
		model.setModelName(className + "");
		model.setModelClass(Contants.Model.getPackagename(className) +"." + className + "");
		model.setPackageName(Contants.Dao.getPackagename(className));
		
		
		model.setModelDesc(DBUtil.getTableNote(tableName));
		return model;
	}
}
